<template>
  <el-container class="cart-container">
    <el-main>
      <el-card>
        <template #header>
          <div class="card-header">
            <h2>我的购物车</h2>
            <el-button 
              type="danger" 
              :icon="DeleteIcon" 
              @click="handleClearCart"
              :disabled="!cartItems.length || loading"
              text
            >
              清空购物车
            </el-button>
          </div>
        </template>

        <div v-if="loading" class="loading-spinner">
          <el-progress :percentage="50" :indeterminate="true" />
          <p>加载购物车中...</p>
        </div>
        <div v-else-if="error" class="error-message">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
        <div v-else-if="cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车还是空的，快去挑选商品吧！">
            <el-button type="primary" @click="goToProducts">去购物</el-button>
          </el-empty>
        </div>
        <div v-else>
          <el-table :data="cartItems" style="width: 100%">
            <el-table-column label="商品图片" width="120">
              <template #default="scope">
                <img 
                  :src="scope.row.thumbnail_url || 'https://via.placeholder.com/80x80.png?text=No+Image'" 
                  alt="商品图片" 
                  class="cart-item-image"
                  @click="goToProductDetail(scope.row.slug)"
                />
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template #default="scope">
                <router-link :to="{ name: 'ProductDetail', params: { slug: scope.row.slug } }">
                  {{ scope.row.name }}
                </router-link>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="120">
              <template #default="scope">¥{{ scope.row.price }}</template>
            </el-table-column>
            <el-table-column label="数量" width="180">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  :max="scope.row.stock_quantity" 
                  size="small"
                  @change="(currentValue, oldValue) => handleQuantityChange(scope.row, currentValue, oldValue)"
                />
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120">
              <template #default="scope">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  :icon="DeleteIcon" 
                  size="small" 
                  circle 
                  @click="handleRemoveItem(scope.row.cart_item_id, scope.row.name)"
                />
              </template>
            </el-table-column>
          </el-table>

          <div class="cart-summary">
            <p>商品总数: <strong>{{ cartSummary.total_quantity || 0 }}</strong> 件</p>
            <p>合计金额: <span class="total-amount">¥{{ (cartSummary.total_amount || 0).toFixed(2) }}</span></p>
            <el-button 
              type="primary" 
              size="large" 
              @click="goToCheckout"
              :disabled="!cartItems.length"
            >
              去结算
            </el-button>
          </div>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import cartService from '../api/cart.service';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete as DeleteIcon } from '@element-plus/icons-vue';

const router = useRouter();

const cartData = ref({ items: [], summary: {} }); // 存储原始API返回的购物车数据
const loading = ref(true);
const error = ref(null);

const cartItems = computed(() => cartData.value.items || []);
const cartSummary = computed(() => cartData.value.summary || {});

const fetchCart = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await cartService.getCart();
    // API 返回的数据结构是 { data: itemsArray, meta: summaryObject } 
    // 我们需要将其转换为 cartData.value = { items: [], summary: {} }
    if (response && response.data && response.meta) {
      cartData.value = {
        items: response.data,    // 后端的 'data' 字段是前端的 'items'
        summary: response.meta   // 后端的 'meta' 字段是前端的 'summary'
      };
    } else {
      // 如果响应结构不符合预期，为了避免错误，可以设置为空或记录一个更具体的错误
      cartData.value = { items: [], summary: {} };
      console.warn('获取到的购物车数据结构不符合预期:', response);
      // 可以选择性地设置一个用户可见的错误信息
      // error.value = '购物车数据格式错误'; 
    }
  } catch (err) {
    console.error('获取购物车失败:', err);
    error.value = err.message || '获取购物车数据失败';
    ElMessage.error(error.value);
    cartData.value = { items: [], summary: {} }; // 出错时也清空数据
  } finally {
    loading.value = false;
  }
};

const handleQuantityChange = async (item, currentValue, oldValue) => {
  if (currentValue === oldValue || currentValue < 1) return; // 数量未变或无效则不作处理
  try {
    await cartService.updateItemQuantity(item.cart_item_id, currentValue);
    ElMessage.success(`商品 "${item.name}" 数量已更新`);
    // 更新成功后，重新获取购物车数据以保证一致性
    await fetchCart(); 
  } catch (err) {
    console.error('更新商品数量失败:', err);
    ElMessage.error(err.message || '更新商品数量失败');
    // 数量改回去
    item.quantity = oldValue;
  }
};

const handleRemoveItem = (cartItemId, itemName) => {
  ElMessageBox.confirm(`确定要从购物车中移除商品 "${itemName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await cartService.removeItem(cartItemId);
      ElMessage.success(`商品 "${itemName}" 已从购物车移除`);
      await fetchCart(); // 重新获取购物车数据
    } catch (err) {
      console.error('移除商品失败:', err);
      ElMessage.error(err.message || '移除商品失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

const handleClearCart = () => {
  ElMessageBox.confirm('确定要清空购物车中的所有商品吗?', '警告', {
    confirmButtonText: '确定清空',
    cancelButtonText: '取消',
    type: 'error',
  }).then(async () => {
    try {
      await cartService.clearCart();
      ElMessage.success('购物车已清空');
      await fetchCart(); // 重新获取购物车数据
    } catch (err) {
      console.error('清空购物车失败:', err);
      ElMessage.error(err.message || '清空购物车失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

const goToProducts = () => {
  router.push({ name: 'Products' });
};

const goToProductDetail = (slug) => {
  if (slug) {
    router.push({ name: 'ProductDetail', params: { slug } });
  }
};

const goToCheckout = () => {
  router.push({ name: 'Checkout' }); // 假设结算页路由名为 'Checkout'
};

onMounted(() => {
  fetchCart();
});

</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-spinner,
.error-message,
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.cart-item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  cursor: pointer;
}

.cart-summary {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  text-align: right;
}

.cart-summary p {
  margin: 10px 0;
  font-size: 16px;
}

.total-amount {
  font-size: 20px;
  color: #ff4d4f;
  font-weight: bold;
}

.cart-summary .el-button {
  margin-top: 15px;
}
</style> 